package logic

import (
	"context"
	"errors"
	"user/models/mysql"
	"user/pkg"

	"user/internal/svc"
	"user/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealnameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealnameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealnameLogic {
	return &RealnameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RealnameLogic) Realname(in *user.RealnameRequest) (*user.RealnameResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var r mysql.UserRealName
	r.UserId = int(in.UserId)
	if err = r.RealName(); err != nil {
		logx.Error("实名认证过失败")
		return nil, err
	}
	if r.ID > 0 {
		logx.Error("用户已实名")
		return nil, errors.New("用户已实名")
	}

	r.Realname = in.Realname
	r.IDCard = in.IdCard
	if !pkg.AuthRealName(in.IdCard, in.Realname) {
		logx.Error("实名失败")
		return nil, err
	}

	if err = r.CreateRealname(); err != nil {
		logx.Error("实名失败")
		return nil, err
	}
	return &user.RealnameResponse{
		Id: int64(r.ID),
	}, nil
}
